<template>
  <div class="hello-container">
    <img src=../assets/get.png style="display:none" ref="alipay" />
    <lemon-imui :width="chatWidth" :height="chatHeight" :hideMenu="hideMenu" :simple="simple" :avatar-cricle="true"
      :hide-message-name="false" :hide-message-time="false" :user="userData" @pull-messages="handlePullMessages"
      @change-contact="handleChangeContact" @send="handleSend" ref="IMUI" />
    <imageEditor ref="imageEditor" />
  </div>
</template>

<script>
// 生成消息唯一索引
import EmojiData from "../database/emoji";
import MyWebSocket from "./MyWebsocket";
import imageEditor from "./ImageEditor";
import request from '@/utils/request';
import qs from 'qs';
import { mapState } from "vuex";
import { getCookie, setCookie } from "@/utils/auth";
export default {
  name: "HomeView",
  props: {
    msg: String,
  },
  computed: {
    ...mapState({
      userData: (state) => state.user.userData,
      contactsData: (state) => state.contacts.contactsData,
      messageList: (state) => state.messageList.messageList,
    }),
    hasLogin() {
      return getCookie("token");
    },
  },
  components: { imageEditor },
  data() {
    return {
      chatWidth: this.resize(),
      websocket: null,
      currentContactId: 1, //当前联系人id
      chatType: "chat", // chat |  code
      accountId: 1000,
      repeatStr: "欢迎体验AI聊天,made by 沈大仙 欢迎来拼车群",
      unLoginMsgObj: {}, //未登录前，发送的消息,
      hideMenu: true,
      simple: true,
      websocketIsError: false,
      openDialog: false,
    };
    let isMaxSize = false;
    let editImg = false;//ture修改图像模式
  },
  mounted() {
    this.initChat();
    //this.getUserAiTimes();
    window.onresize = () => {
      this.resize();
    };
    this.resize();
    this.removeAllDialogByUid();
  },
  methods: {
    getPicture(e) {
     // this.$refs.IMUI.setEditorValue("e.target.files[0]");
    },
    generateRandId() {
      return Math.random().toString(36).substr(-8);
    },
    initChat() {
      if (this.hasLogin) this.$store.dispatch("messageList/initMsgList", { id: this.currentContactId });
      if (this.$refs.IMUI) {
        this.$refs.IMUI.initContacts(this.contactsData);
        // this.$refs.IMUI.initEmoji(EmojiData);
        // 自定义工具栏
        this.initEditorTools1();
        this.$refs.IMUI.changeContact(this.currentContactId);
      }
    },
    resize() {
      this.chatWidth = document.documentElement.clientWidth > 850 && !this.isMaxSize ? 850 : document.documentElement.clientWidth - (this.isMaxSize ? 40 : 48);
      this.chatHeight = document.documentElement.clientHeight > 580 && !this.isMaxSize ? 580 : document.documentElement.clientHeight - (this.isMaxSize ? 40 : 48);
    },
    getUserAiTimes() {
      let contact = this.$refs.IMUI.getCurrentContact();
      request.post('/p/msg/getUserAiTimes').then(res => {
        if (res.state == 1 && res.data != null) {
          this.createMsgObj("您的剩余对话额度为" + res.data + "。", this.$refs.IMUI.getCurrentContact(), "text");
        } else {
          console.log("不知道啥错误了");
          this.$message.error('不知道啥错误了');
        }
      });
    },
    initEditorTools1() {
      let that = this;
      let tools = [
        {
          name: "changeMode",
          isRight: false,
          title: "切换AI",
          click: () => {
            that.simple = !that.simple;
            that.dialogOfAccount = true;
            that.initEditorTools2();
          },
          render: () => {
            return <span style="color:red">切换AI</span>;
          },
        },
        {
          name: "order",
          isRight: false,
          title: "剩余对话额度",
          click: () => {
            that.getUserAiTimes();
          },
          render: () => {
            return <span style="color:#333">对话额度</span>;
          },
        },
        {
          name: "maxSize",
          isRight: false,
          title: "全屏",
          click: () => {
            that.isMaxSize = !that.isMaxSize;
            that.resize();
          },
          render: () => {
            return <span style="color:#333">全屏</span>;
          },
        },
        {
          name: "clearHistory",
          isRight: false,
          title: "清空",
          click: () => {
            that.removeAllMessage();
            that.removeAllDialogByUid();
          },
          render: () => {
            return <span>清空</span>;
          },
        },
        {
          name: "logout",
          isRight: false,
          title: "切换用户",
          click: () => {
            //that.dialogOfAccount = true;
            that.$router.replace({ path: '/login' });
          },
          render: () => {
            return <span>注销</span>;
          },
        }, {
          name: "uploadImage",
          isRight: true,
          title: "编辑图片",
        },
      ];
      this.$refs.IMUI.initEditorTools(tools);
    },
    initEditorTools2() {
      let that = this;
      let tools = [{
        name: "changeMode",
        isRight: false,
        title: "返回",
        click: () => {
          that.simple = !that.simple;
          that.dialogOfAccount = true;
          that.$forceUpdate();
          this.initEditorTools1();
        },
        render: () => {
          return <span style="color:#333">返回</span>;
        },
      }];
      this.$refs.IMUI.initEditorTools(tools);
    },
    // 根据id获取联系人信息
    getContact(id) {
      const data = this.contactsData.find((contact) => contact.id == id);
      return { id: data.id, avatar: data.avatar, displayName: data.displayName };
    },
    createMsgObj(msgStr, contact, type = null) {
      let that = this;
      let msg = {
        id: this.generateRandId(),
        status: "succeed",
        type: type != null ? type : contact.id == 3 ? "image" : "text",
        sendTime: new Date().getTime(),
        content: msgStr,
        toContactId: contact.id,
        fromUser: contact,
      };
      this.appendMessage(msg);
    },
    showAlipay(contact) {
      let that = this;
      let msgObj = {
        id: this.generateRandId(),
        status: "succeed",
        type: "image",
        sendTime: new Date().getTime(),
        content: this.$refs.alipay.src,
        toContactId: contact.id,
        fromUser: contact,
      };
      this.appendMessage(msgObj);
    },
    handlePullMessages(contact, next) {
      let that = this;

      //从后端请求消息数据，包装成下面的样子
      let msg = {
        id: this.generateRandId(),
        status: 'succeed',
        type: 'text',
        sendTime: new Date().getTime(),
        content: contact.lastContent,
        toContactId: contact.id, //接收消息的联系人ID
        fromUser: contact,
      };
      const messages = [msg];
      next(messages, true); //历史消息
    },
    handleChangeContact(contact) {
      this.currentContactId = contact.id;
      this.simple = true;
      this.initEditorTools1();
    },
    handleSend(message, next, file) {
      let contact = this.$refs.IMUI.getCurrentContact();
      if (file) {
        if (contact.id != 3) {
          this.createMsgObj("对不起，本AI不对图片做识别，请换一位为您服务哦。", contact, "text");
          next();
          return;
        }
        // if (file.size > 4 * 1024 * 1024) {
        //   this.createMsgObj("图片太大了，我只接受4MB以下的图片哦，请尝试压缩图片。", contact, "text");
        //   next();
        //   return;
        // }
        // if (file.name.substr(file.name.length - 4, 4) != ".png") {
        //   this.createMsgObj("图片格式不对，我只接受.png格式哦，请尝试改变格式。", contact, "text");
        //   next();
        //   return;
        // }

        this.$refs.imageEditor.dialogVisible = true;

        //转化为blob
        let reader = new FileReader();
        reader.onload = (e) => {
          let data
          if (typeof e.target.result === 'object') {
            data = window.URL.createObjectURL(new Blob([e.target.result]))
          } else {
            data = e.target.result
          }
          this.$refs.imageEditor.option.img = data;
          this.editImg = true;
          next();
        }
        //转化为base64
        reader.readAsDataURL(file);

        return;
        let param = new FormData();
        param.append('file', file);
        let config = {
          headers: { 'Content-Type': 'multipart/form-data' }
        };
        request.post('/p/msg/uploadImg', param, config).then(res => {
          this.createMsgObj("恭喜你，成功上传一张图片，请描述你希望对这张图片做什么修改？", contact, "text");
          this.editImg = true;
          next();
        }, err => {
          console.log("出错了！", err.response);
          this.createMsgObj("网络错误，你可以选择重新上传一张图片。", contact, "text");
          next();
        }
        );
        return;
      }
      //发送消息！
      let aiId = this.$refs.IMUI.getCurrentContact().id;
      aiId = aiId == 3 && this.editImg ? 6 : aiId;
      this.editImg = false;
      let params = {
        msg: message.content,
        aiId: aiId
      };
      request.post('/p/msg/sendAiMsg', qs.stringify(params)).then(res => {
        next();
        if (res.state == 1 && res.data != null) {

          if (res.data.indexOf("对[白云]进行充值") > -1) {
            this.createMsgObj(res.data, contact, "text");
            this.showAlipay(contact);
          } else {
            this.createMsgObj(res.data, contact);
          }
        } else {
          this.createMsgObj(res.data, "对不起，我不想忽悠你，这个问题我无法回答。");
        }
      });
      this.$store.dispatch("messageList/pushMsg", { id: this.currentContactId, msgObj: message });
    },
    closeDialog(dialog) {
      this[dialog] = false;
    },
    getMessages(contactId) {
      let msgList = this.$refs.IMUI.getMessages(contactId);
      return msgList;
    },
    getEditorValue() {
      return this.$refs.IMUI.getEditorValue();
    },
    // 设置编辑框内容
    setEditorValue(str) {
      this.$refs.IMUI.setEditorValue(str);
    },
    appendMessage(msgObj) {
      this.$refs.IMUI.appendMessage(msgObj, true);
      this.$store.dispatch("messageList/pushMsg", { id: this.currentContactId, msgObj });
    },
    removeAllMessage() {
      let msgList = JSON.parse(JSON.stringify(this.getMessages(this.currentContactId)));
      if (this.currentContactId == 3) { //不是修改图像
        this.editImg = false;
      }
      console.log("删除消息：" + this.currentContactId)
      msgList.forEach((msgObj) => {
        this.removeMessage(msgObj.id);
      });
      this.$store.dispatch("messageList/initMsgList", { id: this.currentContactId, initMsgList: [] });
    },
    removeMessage(msgId) {
      this.$refs.IMUI.removeMessage(msgId);
      this.$store.dispatch("messageList/removeMsgById", { id: this.currentContactId, msgId });
    },
    validateAccount() {
      this.$alert("密码不对,聊天关闭,请修改设置", "提示")
        .then(() => {
          this.dialogOfAccount = true;
        })
        .catch(() => { });
    },
    removeAllDialogByUid() {
      request.post('/p/msg/removeAllDialogByUid').then(res => {

      });
    }
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
h3 {
  margin: 40px 0 0;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: inline-block;
  margin: 0 10px;
}

a {
  color: #42b983;
}

.hello-container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  padding: 24px;
  background-image: url(@/assets/bg.webp);
  background-size: 130% 110%;

  ::v-deep .lemon-wrapper {
    border-radius: 10px;
    overflow: hidden;
  }

  ::v-deep .lemon-editor {
    border-top: 1px solid #ccc;
  }
}
</style>
